package File;

import java.io.*;
import java.util.Scanner;


public class Homework3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的根目录:");
        String rootDirPath = scanner.next();
        File rootDir = new File(rootDirPath);
        if(!rootDir.isDirectory()){
            System.out.println("你输入的不是根目录");
            return;
        }

        System.out.println("请输入你要查找的关键字:");
        String keyword = scanner.next();

        scanDir(rootDir,keyword);
    }

    private static void scanDir(File rootDir, String keyword) {
        File[] files = rootDir.listFiles();
        if(files == null || files.length == 0){
            return;
        }
        for(File file : files){
            if(file.isFile()){
                // 如果是普通文件,判断文件名或者文件内容是否包含关键字
                dealFile(file,keyword);
            } else{
                // 如果是目录,就递归调用本方法
                scanDir(file,keyword);
            }
        }
    }

    private static void dealFile(File file, String keyword) {
        if(file.getName().contains(keyword)){
            System.out.println("文件名包含关键字: " + file.getAbsolutePath());
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)){
            while(true){
                char[] buf = new char[1024];
                int len = 0;
                len = reader.read(buf);
                if(len == -1){
                    break;
                }
                stringBuilder.append(buf,0,len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if(stringBuilder.indexOf(keyword) >= 0){
            System.out.println("文件内容包含关键字:" + file.getAbsolutePath());
        }
        return;
    }

}
